package com.example.demo.service;

import com.example.demo.model.UserInfo;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.UserInfo;
import com.example.demo.util.PasswordUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    private static final Logger log = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserMapper userMapper;
    // 用户注册
    public boolean register(String username, String password, String phone) {
        // 检查用户名是否已存在
        UserInfo existUser = userMapper.selectByUsername(username);
        if (existUser != null) {
            return false;
        }
        
        // 创建新用户
        UserInfo user = new UserInfo();
        user.setUsername(username);
        user.setPassword(password);  // 密码已在Controller层加密
        user.setPhone(phone);
        user.setStatus(1);  // 设置用户状态为正常
        
        // 插入用户
        return userMapper.insert(user) > 0;
    }
    // 通过名称查询用户-->用于登录的验证
    public UserInfo selectByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    public UserInfo getAddress(int uid) {
        UserInfo user = userMapper.selectById(uid);
        return convertToUserInfo(user);
    }

    public UserInfo getUserInfo(int uid) {
        UserInfo user = userMapper.selectById(uid);
        return convertToUserInfo(user);
    }

    public int changePassword(String newPassword,int uid) {
        return userMapper.changePassword(newPassword,uid);
    }

    public int updateUserInfo(UserInfo userInfo) {
        log.info("Service层更新用户信息: {}", userInfo);
        try {
            log.info("执行SQL更新，参数：id={}, nickname={}, avatar={}, phone={}", 
                userInfo.getId(), userInfo.getNickname(), 
                userInfo.getAvatar(), userInfo.getPhone());
            // 检查参数是否为空
            if (userInfo.getId() == null) {
                log.error("用户ID为空");
                return 0;
            }
            if (userInfo.getNickname() == null && userInfo.getAvatar() == null && userInfo.getPhone() == null) {
                log.error("所有更新字段都为空");
                return 0;
            }
            
            int result = userMapper.updateUserInfo(userInfo);
            log.info("数据库更新结果: {} (0=失败, 1=成功)", result);
            return result;
        } catch (Exception e) {
            log.error("更新用户信息失败: " + e.getMessage(), e);
            throw e;
        }
    }

    public UserInfo login(String username, String password) {
        // 查询用户
        UserInfo user = userMapper.selectByUsername(username);
        if (user == null) {
            return null;
        }

        // 验证密码
        if (!PasswordUtil.decrypt(password, user.getPassword())) {
            return null;
        }

        // 检查用户状态
        if (user.getStatus() != 1) {
            return null;
        }

        // 转换为UserInfo对象
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        userInfo.setPhone(user.getPhone());
        userInfo.setStatus(user.getStatus());
        userInfo.setCreateTime(user.getCreateTime());
        userInfo.setUpdateTime(user.getUpdateTime());
        userInfo.setAvatar(user.getAvatar());
        userInfo.setNickname(user.getNickname());
        log.info("转换用户信息: 原始用户={}, 转换后={}", user, userInfo);

        return userInfo;
    }

    // 添加转换方法
    private UserInfo convertToUserInfo(UserInfo user) {
        if (user == null) {
            return null;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        userInfo.setPassword(user.getPassword());
        userInfo.setPhone(user.getPhone());
        userInfo.setStatus(user.getStatus());
        userInfo.setCreateTime(user.getCreateTime());
        userInfo.setUpdateTime(user.getUpdateTime());
        // 不再设置avatar字段，因为UserInfo类中没有这个字段
        return userInfo;
    }

    public UserInfo getUserDetail(Integer userId) {
        return userMapper.getUserDetail(userId);
    }

    public UserInfo getUserById(Integer userId) {
        return userMapper.getUserById(userId);
    }

    /**
     * 更新用户信誉分
     * @param userId 用户ID
     * @param change 信誉分变化值
     * @return 更新是否成功
     */
    public boolean updateUserReputation(Integer userId, double change) {
        try {
            // 获取用户当前信誉分
            UserInfo user = userMapper.selectById(userId);
            if (user == null) {
                return false;
            }
            
            // 计算新的信誉分
            double currentScore = user.getCreditScore() != null ? user.getCreditScore() : 2.5; // 默认信誉分为2.5
            double newScore = currentScore + change;
            
            // 限制信誉分范围在0-5之间
            newScore = Math.min(5.0, Math.max(0.0, newScore));
            
            // 更新信誉分
            UserInfo updateUser = new UserInfo();
            updateUser.setId(userId);
            updateUser.setCreditScore(newScore);
            
            int result = userMapper.updateById(updateUser);
            return result > 0;
        } catch (Exception e) {
            log.error("更新用户信誉分失败", e);
            return false;
        }
    }

}
